﻿using Baidu.Aip.Speech;
using NAudio.Wave;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Media;
using System.Text;
using System.Windows.Forms;

namespace 百度AI语音合成
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        // 设置APPID/AK/SK
        string APP_ID = "11627945";
        string API_KEY = "2GmEAqn8EGILhQZGRBGAoaMG";
        string SECRET_KEY = "GQTxbt8FcGK8tkvv3UhdCQSbVlsilRO7";
        private Tts _ttsClient;
       

        // 合成
        public void Tts(string str)
        {
            _ttsClient = new Tts(API_KEY, SECRET_KEY);

            // 可选参数
            Dictionary<string, object> option = new Dictionary<string, object>()
            {
                {"spd", 5}, // 语速
                {"vol", 10}, // 音量
                {"per", 4}  // 发音人，4：情感度丫丫童声
            };
            var result = _ttsClient.Synthesis(str, option);

            if (result.Success)  // 或 result.Success
            {
                File.WriteAllBytes("合成的语音文件本地存储地址.mp3", result.Data);
                
                Mp3ToWav("合成的语音文件本地存储地址.mp3", "合成的语音文件本地存储地址.wav");//mp3转wav文件
                SoundPlayer player = new SoundPlayer();//进行语音文件播放
                player.SoundLocation = "合成的语音文件本地存储地址.wav";
                player.Load(); //同步加载声音  
                player.Play(); //启用新线程播放  
            }
        }

        /// <summary>
        /// MP3文件转WAV
        /// </summary>
        /// <param name="mp3File">MP3文件路径</param>
        /// <param name="outputFile">WAV文件输出目录</param>
        /// <returns></returns>
        public static string Mp3ToWav(string mp3File, string outputFile)
        {
            using (Mp3FileReader reader = new Mp3FileReader(mp3File))
            {
                var newFormat = new WaveFormat(8000, 8, 1); // 8kHz, 8bit
                using (var conversionStream = new WaveFormatConversionStream(newFormat, reader))
                {
                    WaveFileWriter.CreateWaveFile(outputFile, conversionStream);
                }
                return outputFile;
            }
        }

        private void btn_Click(object sender, EventArgs e)
        {
            string str = txt.Text;
            Tts(str);
        }

    }
}
